<?php

class Order_model extends CI_Model {
	
	public $userId;
	public $productId;
	public $since;
	public $quantity;
	public $tax;
	public $discount;
	public $status;
	public $payment;
	public $shipment;
	
	public function editStatus($id, $status) {
		$this->db->where('id', $id);
		$this->db->update('orders', array('status'=>$status));
	}
	
	public function getDetail($id)	{
		$this->db->select('orders.*, products.discount, price, products.name, users.id AS userId, users.name AS username, address, phone');
		$this->db->from('orders');
		$this->db->where('orders.id', $id);
		$this->db->join('products', 'products.id = productId');
		$this->db->join('users', 'users.id = userId');
		return $this->db->get()->result();
	}
	
	public function listOrders($id = null)	{
		$this->db->select('orders.*, products.name');
		$this->db->from('orders');
		if ($id != null)
			$this->db->where('orders.userId', $id);
		$this->db->join('products', 'products.id = productId');
		$this->db->order_by('orders.since', 'desc');
		return $this->db->get()->result();
	}
	
	public function addPending($userId, $payment)	{
		$this->db->where('userId', $userId);
		$this->db->where('status', 0);
		$this->db->update('orders', array('status'=>1, 'payment'=>$payment));
	}
	
	public function getPending($userId)	{
		//$this->db->where('sessionId', $sessionId);
		$this->db->where('userId', $userId);
		$this->db->where('status', 0);
		$this->db->from('orders');
		$this->db->join('products', 'products.id = orders.productId');
		return $this->db->get()->result();
	}
	
	public function hasCheckedOut($userId, $productId)	{
		$this->db->where('userId', $userId);
		$this->db->where('productId', $productId);
		$this->db->where('status', 0);
		$result = $this->db->get('orders', 1, 0)->result();
		return (!empty($result));
	}
	
	public function add($userId, $productId, $sessionId)	{
		$this->userId = $userId;
		$this->productId = $productId;
		$this->sessionId = $sessionId;
		$this->quantity = 1;
		$this->payment = 1;
		$this->shipment = 0;
		$this->status = 0;
		$this->tax = 0;
		$this->discount = 0;
		$this->db->insert('orders', $this);
	}
}
?>
